Python Tutorial 3

Flappy Turtle

Tzer-jen Wei


In [ ]:
from turtle import *

In [ ]:
screensize(216, 500)
setup(288, 512)

In [ ]:
import glob
glob.glob("*.gif")

In [ ]:
for f in glob.glob("*.gif"):
    addshape(f)

In [ ]:
shape("bird2.gif")
up()
speed(0)

Add a background


In [ ]:
bgpic("bg1.gif")

Try main loop


In [ ]:
mainloop()

Add a exit key


In [ ]:
onkey(bye, 'q')
listen()

In [ ]:
mainloop()

put everything together


In [ ]:
from turtle import *
import glob
def turtle_setup():
    screensize(216, 500)
    setup(288, 512)
    for f in glob.glob("*.gif"):
        addshape(f)
    shape("bird2.gif")
    up()
    speed(0)
    bgpic("bg1.gif")
    onkey(bye, 'q')
    listen()

Update Bird Fly Animation


In [ ]:
from time import time       
turtle_setup()
start_time = time()
def update():
    t = time() - start_time
    shape("bird%d.gif" % abs(int(t * 4) % 4 - 1))
    ontimer(update, 10)
update()
mainloop()

Put into a class


In [ ]:
from time import time
class Game:
    def __init__(self):
        turtle_setup()
        self.start_time = time()
        self.update()        
        mainloop()
    def update(self):
        t = time() - self.start_time
        shape("bird%d.gif" % abs(int(t * 4) % 4 - 1))
        ontimer(self.update, 10)

In [ ]:
game = Game()

Let the bird fly


In [ ]:
from math import sin
def update(self):
    t = time() - self.start_time
    goto(0, 50*sin(t))
    shape("bird%d.gif" % abs(int(t * 4) % 4 - 1))
    ontimer(self.update, 10)
Game.update = update

In [ ]:
game = Game()

In [ ]:
turtle_setup()
shape('ground.gif')

In [ ]:
def GIFTurtle(fname):
    t = Turtle(fname + ".gif")
    t.speed(0)
    t.up()
    return t

In [ ]:
from time import time
from math import sin
bg_width = 286
class Game:
    def __init__(self):
            turtle_setup()
            self.grounds = [GIFTurtle("ground") for i in range(3)]
            self.start_time = time()
            self.update()             
            mainloop()
    def update(self):
        t = time() - self.start_time
        goto(0, 50*sin(t))
        shape("bird%d.gif" % abs(int(t * 4) % 4 - 1))
        x = int(t * 100)
        bg_base = -(x % bg_width)
        for i in range(3):
            self.grounds[i].goto(bg_base + bg_width * (i - 1), -200)
        ontimer(self.update, 10)

In [ ]:
Game()

In [ ]:
%run flappybird.py

In [ ]:
%load flappybird.py